import network
import urequests
import json
from machine import Pin, I2C,RTC
from ssd1306 import SSD1306_I2C
from oled_zh import chinese
import time


def get_yy():
    head = {'User-Agent': 'Mozilla/5.0'}
    t_url = r'http://quan.suning.com/getSysTime.do'
    r = urequests.get(url=t_url,headers=head).text
    r = json.loads(r)#把数据转换成json串表达式
    res=r.get('sysTime2')
    week=6
    
    year=int(res.split()[0].split('-')[0])
    month=int(res.split()[0].split('-')[1])
    day=int(res.split()[0].split('-')[2])
    hrs=int(res.split()[1].split(':')[0])
    minute=int(res.split()[1].split(':')[1])
    sec=int(res.split()[1].split(':')[2])
    rtc = RTC()
    rtc.datetime((year, month, day, week, hrs, minute, sec, 0))
    return res,rtc
    

def conn():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect('MA6U', '13811175723')
        while not wlan.isconnected():pass
    print('连接状态',wlan.isconnected())
    print('连接地址',wlan.ifconfig())

conn()


url='https://www.tianqiapi.com/api/?version=v6&appid=36613524&appsecret=IyOu3Qbu'
requests = urequests.get(url).text
html = json.loads(requests)#把数据转换成json串表达式
city=html['city']
tem=html['tem']
tem1=html['tem1']
tem2=html['tem2']

res,rtc=get_yy()

i2c=I2C(scl=Pin(22),sda=Pin(23))
oled=SSD1306_I2C(128,64,i2c)


x=12
y=5

oled.fill(0)
oled.text('Welcome to the', x, 4+y)
oled.text('time system', x, 30+y)
oled.show()  
time.sleep_ms(1000)    
while True:
    res=rtc.datetime()
    res1="%s/%s/%s" % (res[0],res[1],res[2])
    res2="%s:%s:%s" % (res[4],res[5],res[6])
    oled.fill(0)
    oled.text(res1, 15+x, 4+y)
    oled.text(res2, 15+x,18+y,1)
    chinese(city,15+x,35+y,oled)
    oled.text(":", 45+x, 40+y)
    oled.text(tem1, 55+x, 30+y)
    oled.text(tem, 55+x, 40+y)
    oled.text(tem2, 55+x, 50+y)
    chinese('度',70+x,30+y,oled)
    chinese('度',70+x,40+y,oled)
    chinese('度',70+x,50+y,oled)
    oled.show()
    time.sleep_ms(300)
    
    



